package com.basic.boot.common.reqlimit;

import com.basic.boot.exception.ReqLimitException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author cherrish
 * @time 2019-03-14 11:37
 * @name ReteLimitAspect
 * @desc:
 */
@Slf4j
@Aspect
@Component
public class ReteLimitAspect {
    private final String MESSAGE = "Server is busy now, please try again later!";
    com.google.common.util.concurrent.RateLimiter rateLimiter = com.google.common.util.concurrent.RateLimiter.create(Double.MAX_VALUE);

    @Pointcut("@annotation(com.basic.boot.common.reqlimit.AnRateLimiter)")
    public void pointCut() {
    }


    @Around("pointCut()")
    public Object aroundController(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;

        Method method = methodSignature.getMethod();
        AnRateLimiter rateLimiter = method.getAnnotation(AnRateLimiter.class);
        this.rateLimiter.setRate(rateLimiter.permitsPerSecond());
        if (!this.rateLimiter.tryAcquire(rateLimiter.timeOut(), rateLimiter.timeOutUnit())) {
            log.error(MESSAGE);
            throw new ReqLimitException(MESSAGE);
        }
        return pjp.proceed();
    }
}